package com.shw.system.common.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import com.shw.system.common.utils.StringUtils;

/**
 * Repeatable 过滤器
 * 
 * @author linhai
 */
public class RepeatableFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest)
        {
            if (isJsonRequest((HttpServletRequest) request))
            {
                requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
            }
        }
        if (null == requestWrapper)
        {
            chain.doFilter(request, response);
        }
        else
        {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy()
    {

    }
    
    /**
     * 是否是Json请求
     * 
     * @param request
     */
    public boolean isJsonRequest(HttpServletRequest request)
    {
        String header = request.getHeader(HttpHeaders.CONTENT_TYPE);
        if (StringUtils.isEmpty(header))
        {
            return false;
        }
        return MediaType.parseMediaType(header) == MediaType.APPLICATION_JSON;
    }
}
